package com.evan.review.architecture.components.paging;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Paging示例ViewModel
 */
public class PagingViewModel extends ViewModel {
    
    private final MutableLiveData<List<Item>> items = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    
    private int currentPage = 0;
    private static final int PAGE_SIZE = 20;
    private static final int TOTAL_PAGES = 5; // 模拟总页数
    
    /**
     * 加载初始数据
     */
    public void loadInitialItems() {
        currentPage = 0;
        loadItems();
    }
    
    /**
     * 加载更多数据
     */
    public void loadMoreItems() {
        // 检查是否已经加载完所有页
        if (currentPage >= TOTAL_PAGES) {
            return;
        }
        
        // 检查是否正在加载
        if (Boolean.TRUE.equals(isLoading.getValue())) {
            return;
        }
        
        // 加载下一页
        currentPage++;
        loadItems();
    }
    
    /**
     * 加载数据
     */
    private void loadItems() {
        isLoading.setValue(true);
        
        executorService.execute(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(1500);
                
                // 获取当前列表
                List<Item> currentList = items.getValue();
                if (currentList == null) {
                    currentList = new ArrayList<>();
                }
                
                // 如果是第一页，清空列表
                if (currentPage == 1) {
                    currentList.clear();
                }
                
                // 添加新数据
                int startId = (currentPage - 1) * PAGE_SIZE + 1;
                for (int i = 0; i < PAGE_SIZE; i++) {
                    int id = startId + i;
                    currentList.add(new Item(
                            id,
                            "标题 #" + id,
                            "这是项目 #" + id + " 的详细描述。这是一个演示Paging库的示例项目。"
                    ));
                }
                
                // 更新LiveData
                items.postValue(new ArrayList<>(currentList));
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 更新加载状态
                isLoading.postValue(false);
            }
        });
    }
    
    /**
     * 获取数据列表
     */
    public LiveData<List<Item>> getItems() {
        return items;
    }
    
    /**
     * 获取加载状态
     */
    public LiveData<Boolean> getIsLoading() {
        return isLoading;
    }
    
    @Override
    protected void onCleared() {
        super.onCleared();
        executorService.shutdown();
    }
} 